from django.shortcuts import render, redirect
from django.contrib import messages
from django.views.decorators.csrf import csrf_protect
from django.http import HttpResponse
from user.models import User


# Create your views here.
def index(request):
    return render(request, 'index.html')


def toLogin(request):
    return render(request, 'login.html')


def toRegister(request):
    return render(request, 'register.html')


@csrf_protect
def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        if not username or not password:
            return render(request, 'login.html', {'error_message': '用户名和密码不能为空'})

        try:
            user = User.objects.get(username=username, password=password)
            # 登录成功，可以在这里设置session
            request.session['user_id'] = user.id
            request.session['username'] = user.username
            return redirect('/user/')
        except User.DoesNotExist:
            return render(request, 'login.html', {'error_message': '用户名或密码错误'})
    else:
        return render(request, 'login.html')


@csrf_protect
def register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        age = request.POST.get('age')
        email = request.POST.get('email')
        gender = request.POST.get('gender')

        # 验证必填字段
        if not all([username, password, age, email, gender]):
            return render(request, 'register.html', {'error_message': '所有字段都是必填的'})

        # 检查用户名是否已存在
        if User.objects.filter(username=username).exists():
            return render(request, 'register.html', {'error_message': '用户名已存在，请选择其他用户名'})

        # 检查邮箱是否已存在
        if User.objects.filter(email=email).exists():
            return render(request, 'register.html', {'error_message': '邮箱已被注册，请使用其他邮箱'})

        try:
            # 创建新用户
            User.objects.create(
                username=username,
                password=password,
                age=int(age),
                email=email,
                gender=gender
            )
            return render(request, 'login.html', {'success_message': '注册成功，请登录'})
        except Exception as e:
            return render(request, 'register.html', {'error_message': f'注册失败：{str(e)}'})
    else:
        return render(request, 'register.html')


def logout(request):
    request.session = {}
    messages.success(request, '注销成功')
    return render(request, 'index.html')
